package com.faithnmn.utils.weather;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.io.SAXReader;

import android.util.Log;

import com.faithnmn.utils.weather.model.Weather;

public class YahooParser {


    public static Weather parse(InputStream inputStream) throws Exception {
        Weather weather = new Weather();

        SAXReader xmlReader = createXmlReader();
        Document doc = xmlReader.read( inputStream );

        Log.e( "","Parsing XML Response" );
        weather.setCity( doc.valueOf("/rss/channel/y:location/@city") );
        weather.setRegion( doc.valueOf("/rss/channel/y:location/@region") );
        weather.setCountry( doc.valueOf("/rss/channel/y:location/@country") );
        weather.setCondition( doc.valueOf("/rss/channel/item/y:condition/@text") );
        weather.setTemp( doc.valueOf("/rss/channel/item/y:condition/@temp") );
        weather.setChill( doc.valueOf("/rss/channel/y:wind/@chill") );
        weather.setHumidity( doc.valueOf("/rss/channel/y:atmosphere/@humidity") );
        weather.unit_distance = (doc.valueOf("/rss/channel/y:units/@distance"));
        weather.unit_temp = (doc.valueOf("/rss/channel/y:units/@temperature"));
        weather.unit_pressure = (doc.valueOf("/rss/channel/y:units/@pressure"));
        weather.unit_speed = (doc.valueOf("/rss/channel/y:units/@speed"));
        weather.astronomy_sunrise = (doc.valueOf("/rss/channel/y:astronomy/@sunrise"));
        weather.astronomy_sunset = (doc.valueOf("/rss/channel/y:astronomy/@sunset"));
        weather.atmosphere_pressure = (doc.valueOf("/rss/channel/y:atmosphere/@pressure"));
        weather.wind_chill = (doc.valueOf("/rss/channel/y:wind/@chill"));
        weather.wind_direction = (doc.valueOf("/rss/channel/y:wind/@direction"));
        weather.wind_speed = (doc.valueOf("/rss/channel/y:wind/@speed"));
        weather.condition_code = Integer.parseInt((doc.valueOf("/rss/channel/item/y:condition/@code")));
        doc = null;
        if(inputStream != null){
        	try {
        		inputStream.close();
			} catch (IOException e) {
			}
        }
        xmlReader = null;
        return weather;
    }

    private static SAXReader createXmlReader() {
        Map<String,String> uris = new HashMap<String,String>();
        uris.put( "y", "http://xml.weather.yahoo.com/ns/rss/1.0" );

        DocumentFactory factory = new DocumentFactory();
        factory.setXPathNamespaceURIs( uris );

        SAXReader xmlReader = new SAXReader();
        xmlReader.setDocumentFactory( factory );
        return xmlReader;
    }
}
